<template>
  <div class="main" style="height: 100%;">
    <div style="display: flex;justify-content: space-between;align-items: center;">
      <div style="display: flex;">
        <el-date-picker size="small" style="margin-right:  10px;" v-model="params.time" type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <el-input size="small" prefix-icon="el-icon-search" style="width: 300px;margin-right:  10px;"
                  v-model="params.storeName"
                  clearable
                  placeholder="请输入店铺名称"></el-input>
        <el-select filterable remote :remote-method="remoteMethod" value-key="creator"
                   clearable v-model="params.creator" size='small'
                   style="width:300px;margin-right:  10px;" placeholder="请输入创建人">
          <el-option v-for="(item,i) in creatorList" :key="i" :label="item" :value="item">
          </el-option>
        </el-select>
        <el-select size="small" style="width: 200px;margin-right: 10px;" clearable v-model="params.area" filterable
                   placeholder="请选择省份">
          <el-option v-for="item in provinceOptions" :key="item.area" :label="item.areaName"
                     :value="item.area">
          </el-option>
        </el-select>
        <el-select size="small" style="width: 200px;margin-right: 10px;" clearable v-model="params.status" filterable
                   placeholder="请选择审核状态">
          <el-option label="未完结"
                     value="0">
          </el-option>
          <el-option label="主管已审核"
                     value="1">
          </el-option>
          <el-option label="财务已审核"
                     value="2">
          </el-option>
        </el-select>
        <!--        <el-select size="small" style="width: 200px;margin-right: 10px;" clearable v-model="params.storeType" filterable-->
        <!--                   placeholder="请选择店铺类型">-->
        <!--          <el-option label="新增店铺"-->
        <!--                     value="1">-->
        <!--          </el-option>-->
        <!--          <el-option label="老店翻新"-->
        <!--                     value="2">-->
        <!--          </el-option>-->
        <!--        </el-select>-->
        <el-button size="small" type="primary" @click="searchList">查询</el-button>
      </div>
      <div>
        <el-button style="position: absolute;top: 10px;right: 140px;background-color:#F56C6C;color: #FFFFFF"
                   v-if="userName=='曹紫芳'||userName=='赵伟清'"
                   @click="closeReimburse">
          关闭报销
        </el-button>
        <el-button style="position: absolute;top: 10px;right: 20px;background-color:#66b1ff;color: #FFFFFF"
                   @click="addReimburse">
          新增报销
        </el-button>
      </div>
      <div>
      </div>

    </div>
    <div style="margin-top: 20px;">
      <el-table :data="dataList" :height="maxHeight" v-loading='loading' element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading" tripe border tooltip-effect="dark" :headerCellStyle="{
                    'textAlign': 'center',
                    'fontWeight': 400,
                    'background': '#66b1ff',
                    'color': 'white',
                }" :cellStyle="{
                    'textAlign': 'center',
                    'fontSize': '12px'
                }">
        <el-table-column prop="orderId" label="ID" width="100px"></el-table-column>
        <el-table-column label="门店名称" min-width="200px">
          <template slot-scope="scope">
            <el-link
                :style="{ color: getStatusColor(scope.row.status),borderBottom:getLineColor(scope.row.status) }"
                style="text-decoration: none;border-bottom: solid 1px #409EFF"
                @click="openDialog(scope.row)">
              {{ scope.row.storeName }}
            </el-link>
            <span style="color: #ce0e0f" v-if="scope.row.isRejectionNum>0">(含{{ scope.row.isRejectionNum }}条驳回)</span>
          </template>
        </el-table-column>
        <el-table-column prop="areaName" label="区域" min-width="100px"></el-table-column>
        <el-table-column prop="deliveryDate" label="发货日期" min-width="100px"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 1" type="warning">主管审完</el-tag>
            <el-tag v-if="scope.row.status == 2" type="primary">已完结</el-tag>
            <el-tag v-if="scope.row.status == 0" type="danger">未完结</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="明细操作">
          <template slot-scope="scope">
            <el-link type="warning" @click="checkDetail(scope.row)" v-prevent-re-click style="margin-right: 10px">查看
            </el-link>
            <el-link type="primary" @click="downDetail(scope.row)" v-prevent-re-click>下载</el-link>
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" fixed="right" min-width="100px">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-link style='font-size:12px' type="success" @click="confirmOrder(scope.row.id)"-->
        <!--                     v-if='scope.row.status !== 1'>确认完成-->
        <!--            </el-link>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
    </div>
    <div style="padding-top: 20px;">
      <el-pagination style="border-top:1px solid #eee;padding-top: 20px;" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="params.pageNumber" :page-sizes="[20, 30, 50]"
                     :page-size="20" layout="total, sizes, prev, pager, next, jumper" align="right"
                     :total="params.totalCount">
      </el-pagination>
    </div>
    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="ledgerStatus" width="90%"
               center
               :show-close="false"
               top="10px"
               :before-close="handleClose">
      <div class="feeType">
        <div class="typeList" v-if="resFee&&authority.includes(998)"><span>公里数</span><span>{{ decimalCount }}</span>
        </div>
        <div class="typeList" v-if="authority.includes(998)"><span>报价单运费</span><span>{{ resFee }}</span></div>
        <div :class="chooseDateIndex==item.financeId?'active':''" class="typeList"
             :style="{ color: item.financeTypeStatus === 0 ? 'black' : 'red' }" @click="chooseType(item.financeId)"
             v-for="item in typeList"><span>{{ item.financeName }}</span><span>{{ item.financeTotal }}</span>
        </div>
      </div>
      <div class="feeTable">
        <el-table :data="feeData"
                  @selection-change="handleSelectionChange"
                  style="margin-top: 10px;height: 600px;overflow: scroll"
                  :headerCellStyle="{
                    'textAlign': 'center',
                    'fontWeight': 400,
                    'background': '#66b1ff',
                    'color': 'white',
                }" :cellStyle="{
                    'textAlign': 'center',
                    'fontSize': '12px'
                }">
          <el-table-column prop="id" label="单号" width="70px"></el-table-column>
          <el-table-column prop="userName" label="申请人"></el-table-column>
          <el-table-column prop="createTime" label="申请日期" width="95px"></el-table-column>
          <el-table-column prop="financeLevelTypeName" label="费用类型"></el-table-column>
          <el-table-column prop="optionerName" label="承担主体"></el-table-column>
          <el-table-column prop="matter" label="费用说明" width="230px"></el-table-column>
          <el-table-column prop="money" label="花费"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column prop="rejectReason" label="驳回原因"></el-table-column>
          <el-table-column label="凭证" width="200px">
            <template slot-scope="scope">
              <el-image v-for='i in scope.row.proof' :key="i" style="width: 50px; height: 50px"
                        :src="host+i" :preview-src-list="scope.row.proof.map((img) => host + img)">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="付款方式" width="210px">
            <template slot-scope="scope">
              <div v-if="!scope.row.payUrl" style="display: flex;
         flex-direction: column;justify-content: space-around;height: 100px;width: 210px">
                <span>卡号：{{ scope.row.cardNo }}</span>
                <span>开户行：{{ scope.row.bankName }}</span>
                <span>持卡人：{{ scope.row.cardName }}</span>
              </div>
              <div v-if="scope.row.payUrl">
                <el-image style="width: 50px; height: 50px"
                          :src="host+scope.row.payUrl" :preview-src-list="Array(host+scope.row.payUrl)">
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="财务付款凭证">
            <template slot-scope="scope" v-if="scope.row.paidUrlArr">
              <el-image style="width: 50px; height: 50px"
                        v-for="(url,index) in scope.row.paidUrlArr"
                        :key="index"
                        :src="host+url" :preview-src-list="[host+url]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <div v-if="scope.row.status==3" style="color:seagreen">已付款</div>
              <div v-if="scope.row.status==2" style="color:#f5b330">待付款</div>
              <div v-if="scope.row.status==0" style="color:#f5b330">待主管审核</div>
              <div v-if="scope.row.status==1" style="color:orangered">已驳回</div>
              <div v-if="scope.row.status==4" style="color:#66b1ff">待财务审核</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template slot-scope="scope">
              <div v-if="scope.row.status==0||scope.row.status==4">
                <el-button type="danger" slot="reference" size="small" @click="reject(scope.row)"
                           v-if="[996].some(value => authority.includes(value))&&![4].includes(scope.row.status)">驳回
                </el-button>
                <el-button type="danger" slot="reference" size="small" @click="reject(scope.row)"
                           v-if="[999].some(value => authority.includes(value))&&scope.row.status==4">驳回
                </el-button>
                <el-button type="primary" size="small" @click="directorAudit(scope.row,4)" style="margin-left: 10px"
                           v-if="authority.includes(996)&&![4].includes(scope.row.status)">通过
                </el-button>
              </div>
              <el-link v-if="scope.row.status=='1'&&authority.includes(999)" style="color: red;margin-left: 15px"
                       @click="deleteAudit(scope.row)">删除
              </el-link>
              <el-link v-if="scope.row.status=='1'" style="color: orange;margin-left: 15px"
                       @click="editAudit(scope.row)">编辑
              </el-link>
              <el-link v-if="[2,3].includes(scope.row.status)&&authority.includes(999)"
                       style="text-decoration: none;font-size: 13px"
                       type="primary"
                       @click="comfirmAudit(scope.row,3)"><i class="el-icon-refresh-left"></i>撤回
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
              type="selection"
              v-if="authority.includes(999)"
              :selectable="isRowSelectable"
              width="55">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ledgerStatus = false">返 回</el-button>
        <el-button style="position: absolute;right: 20px" type="primary" @click="checkPayType"
                   v-if="authority.includes(999)&&buttonShow">财务上传打款凭证</el-button>
      </span>

      <el-dialog
          :close-on-click-modal="false"
          width="30%"
          title="财务付款凭证"
          :visible.sync="innerVisible"
          append-to-body>
        <div style="display: flex">
          <span style="margin-right: 30px">财务付款凭证:</span>
          <span style="color: gray; font-size: 12px"
          >(粘贴复制即可上传图片)</span
          >
        </div>
        <div class="div" style="display: flex; align-items: center">
          <div
              v-for="(v, i) in paidUrl"
              style="display: flex; align-items: center; margin-right: 10px;"
          >
            <el-image
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="[host + v]"
            >
            </el-image>
            <div @click="deletePaiedUrl(i)">
              <el-icon name="delete"></el-icon>
            </div>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
                      <el-button @click="innerVisible = false">取 消</el-button>
                      <el-button type="primary" @click="comfirmPay">已付款</el-button>
                  </span>
      </el-dialog>

    </el-dialog>
    <add-reimburse ref="addDialog" @addStatus="receiveMessage"></add-reimburse>
    <el-dialog :close-on-click-modal="false" :visible.sync="closeDialog" center title="选择日期" width="30%">
      日期：
      <el-date-picker
          v-model="time"
          type="date"
          size="small"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width: 80%"
          placeholder="选择日期">
      </el-date-picker>
      <span slot="footer">
        <el-button @click="closeDialog = false">取 消</el-button>
                      <el-button type="primary" @click="comfirmClose">确定</el-button>
      </span>
      <span slot="footer" class="dialog-footer">
        <span style="display: block; color: red"
        >*确定后该日期前的订单不可再继续报销</span
        >
      </span>
    </el-dialog>
    <el-dialog :visible.sync="rejectDialog" title="驳回" center width="30%">
      <el-input v-model="rejectReason" type="textarea" placeholder="请填写驳回原因" size="small"></el-input>
      <!--                <el-button size="small"  @click="visible = false" style="float: right;margin-top:10px ;margin-left: 10px-->
      <!--">取消</el-button>-->
      <span slot="footer">
        <el-button type="danger" size="small"
                   v-if="[999].some(value => authority.includes(value))"
                   @click="comfirmAudit(rejectId,0)">确认驳回
      </el-button>
       <el-button type="danger" size="small"
                  v-if="[996].some(value => authority.includes(value))"
                  @click="directorAudit(rejectId,1)">确认驳回
      </el-button>
     </span>
    </el-dialog>
    <check-detail ref="checkDetailRef"></check-detail>
  </div>

</template>

<script>
import upload from '@/RayComponents/upload.vue'
import dayjs from 'dayjs';
import axios from "axios";
import Decimal from "decimal.js";
import addReimburse from "./addReimburse.vue";
import quinn from "../../../utils/quinn";
import store from "../../../store";
import checkDetail from "./checkDetail.vue";
import ExcelJS from "exceljs";

export default {
  name: "StoreLedger",
  components: {
    upload,
    addReimburse,
    checkDetail
  },
  data() {
    return {
      apiName: "newAreaLedgerList",
      params: {
        pageNumber: 1,
        pageSize: 20,
        time: '',
        storeName: '',
        status: "",
        area: '',
        creator: ''
      },
      payUrl: "",
      previewPayList: [],
      innerVisible: false,
      buttonShow: false,
      closeDialog: false,
      rejectDialog: false,
      loading: false,
      visible: false,
      innerTitle: "",
      cardNo: "",
      rejectId: {},
      paidUrl: [],
      cardName: "",
      userName: "",
      bankName: "",
      totalCount: 0,
      previewImg: [],
      host: this.$imgHost,
      previewImgList: [],
      chooseDateIndex: 1,
      dialogTitle: "",
      rejectReason: "",
      decimalCount: "",
      resFee: "",
      ledgerStatus: false,
      maxHeight: 0,
      typeOptions: [],
      typeList: [],
      createForm: {
        typeId: '',
        provinceId: '',
        voucher: '',
        price: '',
        remark: ''
      },
      orderId: "",
      time: "",
      provinceOptions: [],
      dataList: [],
      authority: [],
      feeData: [],
      arr: [],
      creatorList: []
    };
  },
  watch: {},
  computed: {
    preImgs() {
      return this.paidUrl.map((e) => `${this.$imgHost}${e}`);
    },
    headers() {
      const token = this.token || this.$quinn.getStorage("token");
      return {
        token,
      };
    },
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
    const {authority = []} = quinn.getStorage("userData")
    const {userName = []} = quinn.getStorage("userData") || {};
    this.userName = userName
    this.authority = authority;
  },
  mounted() {
    this.getCostType();
    this.getProvince();
    this.getList();
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 240;
      })
    }
  },
  methods: {
    checkDetail(val) {
      this.$refs.checkDetailRef.handleOpen(val)
    },
    reject(row) {
      this.rejectDialog = true
      this.rejectReason = ''
      this.rejectId = row
    },
    editAudit(row) {
      const data = {
        ...row,
        orderName: this.dialogTitle,
        orderId: this.orderId
      }
      this.$refs.addDialog.handleOpen(data)
    },
    getStatusColor(status) {
      return status === 1
          ? "orange"
          : status === 2
              ? "#66b1ff"
              : status === 0
                  ? "red"
                  : "transparent";
    },
    getLineColor(status) {
      return status === 1
          ? "1px solid orange"
          : status === 2
              ? "1px solid #66b1ff"
              : status === 0
                  ? "1px solid red"
                  : "transparent";
    },
    isRowSelectable(row) {
      return row.status == 4;
    },
    wareHousePass(row) {
      this.$api.storeLedgerUpdateSupervisorStatus({storeLedgerId: row.id}).then(res => {
        if (res == 1) {
          this.$message.success('操作成功！')
          this.chooseType(this.chooseDateIndex)
          // this.ledgerStatus=false
          this.getList()

        }
      })
    },
    remoteMethod(val) {
      if (val) {
        const params = {
          accountName: val
        }
        this.$api.storeLedgerGetAccountName(params).then(res => {
          this.creatorList = res
        })
      }
    },
    receiveMessage(val) {
      if (val == 1) {
        this.getList()
      }
      if (val == 2) {
        this.$api.storeLedgerGetFinanceOneLevelTypeDto({orderId: this.orderId}).then(res => {
          this.typeList = res
        })
        this.chooseType(this.chooseDateIndex)
        this.getList()
      }
    },
    addReimburse() {
      this.$refs.addDialog.handleOpen()
    },
    closeReimburse() {
      this.closeDialog = true
      this.time = ""
    },
    comfirmClose() {
      this.$api.orderCloseOrderReimbursement({closeTime: this.time}).then(res => {
        if (res == 1) {
          this.closeDialog = false
          this.$message.success("操作成功！")
          this.getList()
        }
      })
    },
    handleSelectionChange(e) {
      if (e.toString()) {
        this.buttonShow = true
      } else {
        this.buttonShow = false
      }
      const _arr = e.map(el => el.id)
      this.arr = _arr
    },
    handlePaste(event) {
      if (!this.innerVisible) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': store.state.token
        }
      })
          .then(response => {
            this.paidUrl.push(response.data.result[0]);
            // this.preSalesImgList.push('https://' + response.data.result[0]);
          })
          .catch(error => {
          });
    },
    deletePaiedUrl(i) {
      this.paidUrl.splice(i, 1)

    },
    onSuccess(res) {
      console.log(res)
      const {paidUrl = []} = this;
      if (res.code == 200 && res.result) {
        // paidUrl.push(res.result[0]);
        this.paidUrl = res.result;
      }
    },
    confirmOrder(val) {
      this.$api.storeLedgerUpdateStoreLedgerStatus({id: val}).then(res => {
        this.getList();
      })
    },
    searchList() {
      this.params.pageNumber = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      let params = {
        pageNumber: this.params.pageNumber,
        pageSize: this.params.pageSize,
        startTime: this.params.time ? dayjs(this.params.time[0]).format("YYYY-MM-DD") : '',
        endTime: this.params.time ? dayjs(this.params.time[1]).format("YYYY-MM-DD") : '',
        areaId: this.params.area,
        status: this.params.status,
        storeName: this.params.storeName,
        creator: this.params.creator
        // storeType: this.params.storeType
      }
      this.$api.storeLedgerGetStoreLedger(params).then(res => {
        this.dataList = res.data;
        this.params.totalCount = res.total
        this.loading = false;
      })
    },
    getProvince() {
      this.$api.areaLedgerAreaList().then(res => {
        this.provinceOptions = res;
      })
    },
    getCostType() {
      this.$api.areaLedgerFyTypeList().then(res => {
        this.typeOptions = res;
      })
    },
    // submitCreateForm() {
    //   for (let i in this.createForm) {
    //     if (this.createForm[i] == '') {
    //       this.$message.error('请检查信息!');
    //       return;
    //     }
    //   }
    //   this.ledgerStatus = false;
    // },
    handleSizeChange(e) {
      this.params.pageSize = e;
      this.getList()
    },
    handleCurrentChange(e) {
      this.params.pageNumber = e;
      this.getList()
    },
    async openDialog(row) {
      this.dialogTitle = row.storeName
      this.orderId = row.orderId
      const res = await this.$api.storeLedgerGetFinanceOneLevelTypeDto({orderId: row.orderId}).then()
      const resFee = await this.$api.orderGetOrderExpressCharge({orderId: row.orderId}).then()
      this.resFee = resFee
      if (resFee) {
        const decimalCount = new Decimal(resFee).div(new Decimal(4))
        this.decimalCount = decimalCount
      }
      this.typeList = res
      this.chooseType(this.chooseDateIndex)
      this.ledgerStatus = true
    },
    handleClose() {

    },
    chooseType(val) {
      this.chooseDateIndex = val
      this.$api.storeLedgerSelectFinanceDetailsByFinanceId({financeId: val, orderId: this.orderId}).then(res => {
        this.feeData = res
        res.map(a => {
          a.proof.forEach(el => {
            this.previewImgList.push(this.host + el)
          })
        })

      })
    },
    comfirmAudit(val, type) {
      const data = {
        status: 1,
        id: val.id,
        rejectReason: this.rejectReason
      }
      if (type == 3) {
        data.status = 0
        delete data.rejectReason
      }
      this.$api.storeLedgerUpdateStoreLedgerFinanceStatus(data).then(res => {
        if (res == 1) {
          this.$message({message: "操作成功!", type: "success"})
          this.$api.storeLedgerGetFinanceOneLevelTypeDto({orderId: this.orderId}).then(res => {
            this.typeList = res
          })
          this.chooseType(this.chooseDateIndex)
          this.rejectDialog = false
          this.getList()
        }
      })
    },
    directorAudit(val, type) {
      const data = {
        status: type,
        rejectReason: this.rejectReason,
        storeLedgerId: val.id
      }
      this.$api.storeLedgerUpdateSupervisorStatus(data).then(res => {
        if (res == 1) {
          this.$message({message: "操作成功!", type: "success"})
          this.$api.storeLedgerGetFinanceOneLevelTypeDto({orderId: this.orderId}).then(res => {
            this.typeList = res
          })
          this.chooseType(this.chooseDateIndex)
          this.rejectDialog = false
          this.getList()
        }
      })

    },
    checkPayType(val) {
      this.payId = val.id
      this.innerVisible = true
      this.paidUrl = []
    },
    async comfirmPay() {
      if (!this.paidUrl) {
        return this.$message.warning("请财务上传已付款凭证！");
      }
      const result = this.arr.map(value => ({id: value, status: 3, paidUrl: this.paidUrl.toString()}));
      const res = await this.$api.storeLedgerUpdateStoreLedgerFinanceStatus2(result).then()
      if (res == 1) {
        this.innerVisible = false;
        this.getList()
        this.$api.storeLedgerGetFinanceOneLevelTypeDto({orderId: this.orderId}).then(res => {
          this.typeList = res
        })
        this.chooseType(this.chooseDateIndex)
      }
      // const promises = this.arr.map(el => {
      //   const data = {
      //     id: el,
      //     status: 3,
      //     paidUrl: this.paidUrl.toString()
      //   };
      //   return this.$api.storeLedgerUpdateStoreLedgerFinanceStatus2(data).then(res => {
      //     if (res === 1) {
      //       return Promise.resolve();
      //     } else {
      //       return Promise.reject("操作失败");
      //     }
      //   });
      // });

      // Promise.all(promises)
      //     .then(() => {
      //       this.$message({message: "操作成功!", type: "success"});
      //       this.innerVisible = false;
      //       this.getList()
      //       this.$api.storeLedgerGetFinanceOneLevelTypeDto({orderId: this.orderId}).then(res => {
      //         this.typeList = res
      //       })
      //       this.chooseType(this.chooseDateIndex)
      //     })
      //     .catch(error => {
      //       this.$message.error(error || "部分操作失败");
      //     });
    },
    //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线
    async deleteAudit(row) {
      const r = await this.$confirm("确认删除吗？", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(() => null);
      if (r) {
        const res = await this.$api.storeLedgerDeleteOrUpdateStoreLedger({id: row.id}).catch(() => null);
        if (res == 1) {
          this.$message.success('操作成功!')
          this.chooseType(this.chooseDateIndex)

        }
      }
    },
    getImageBase64(url) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.onload = function () {
          try {
            const canvas = document.createElement('canvas')
            canvas.width = img.width
            canvas.height = img.height
            const ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0)
            console.log(ctx, "ctx")
            resolve(canvas.toDataURL('image/jpeg')) // ✅ 修正为标准 MIME
          } catch (e) {
            reject(e)
          }
        }
        img.onerror = reject
        img.src = url + (url.includes('?') ? '&' : '?') + 'v=' + Date.now() // 防缓存
      })
    },
    async downDetail(row) {
      this.downIsLoad = true
      const res = await this.$api.storeLedgerGetStoreReimburseDetail({orderId: row.orderId})
      this.$message('正在导出，请稍等~')
      const workbook = new ExcelJS.Workbook()
      const worksheet = workbook.addWorksheet('Sheet1')
      const headers = [
        '申请人', '申请日期', '费用类型',
        '承担主体', '费用说明', '金额/花费',
        '备注', '凭证', '付款方式', '财务付款凭证', '状态',
      ]
      const titleRow = worksheet.addRow(headers)
      worksheet.columns = headers.map((item, index) => {
        if (index == 4) {
          // 交易截图
          return {
            width: 80,
            alignment: {vertical: 'middle', horizontal: 'center'} // 所有列居中
          }
        } else {
          return {
            width: 20,
            alignment: {vertical: 'middle', horizontal: 'center'} // 所有列居中
          }
        }
      });
      // 标题样式
      titleRow.eachCell((cell) => {
        cell.fill = {type: 'pattern', pattern: 'solid', fgColor: {argb: '800080'}}
        cell.font = {bold: true, color: {argb: 'FFFFFF'}}
        cell.alignment = {
          wrapText: true,             // 自动换行
          vertical: 'middle',         // 垂直居中
          horizontal: 'center',       // 水平居中（可按需）
        }
      })
      for (const el of res) {
        const statusMap = ['待主管审核', '已驳回', '待付款', '已付款', '待财务审核']
        el.storeTypeName = statusMap[el.status] || ''
        const rowItem = worksheet.addRow([
          el.userName,
          el.createTime,
          el.levelName,
          el.optioner,
          el.matter,
          el.money,
          el.remark,
          // el.rejectReason,
          '',
          '',
          '',
          el.storeTypeName,
        ])
        const images = Array.isArray(el.proof) ? el.proof : el.proof ? [el.proof] : []
        const images1 = Array.isArray(el.payUrl) ? el.payUrl : el.payUrl ? [el.payUrl] : []
        const images2 = Array.isArray(el.paidUrl) ? el.paidUrl : el.paidUrl ? [el.paidUrl] : []
        const imageHeight = 80
        const imageWidth = 100
        const gap = 10
        if (images.length > 0) {
          worksheet.getRow(rowItem.number).height = imageHeight + 10
          const imageGroups = [
            {list: images, col: 7},
            {list: images1, col: 8},
            {list: images2, col: 9},
          ]
          for (const group of imageGroups) {
            const list = group.list || []
            const baseCol = group.col

            for (let i = 0; i < list.length; i++) {
              try {
                const base64 = await this.getImageBase64('https://' + list[i])
                const imageId = workbook.addImage({base64, extension: 'jpeg'})
                worksheet.addImage(imageId, {
                  tl: {col: baseCol, row: rowItem.number - 1, colOff: i * (imageWidth + gap)},
                  ext: {width: imageWidth, height: imageHeight},
                })
              } catch (err) {
                console.warn(`图片插入失败 (第${baseCol}列):`, list[i], err)
              }
            }
          }


        }
      }

      const buffer = await workbook.xlsx.writeBuffer()
      saveAs(new Blob([buffer]), `${row.storeName}.xlsx`)
    }
  }
}
</script>

<style lang="less" scoped>
.amountContainer {
  width: 100%;
  text-align: center;
}

.amountContainer > div:nth-child(1) {
  margin-bottom: 10px;
}

/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .center {
  border-radius: 20px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.feeType {
  display: flex;
  justify-content: center;
}

.typeList {
  width: 150px;
  height: 60px;
  color: #000000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  background: linear-gradient(to left, #b3d8ff, #b3d8ff) left top no-repeat,
  linear-gradient(to bottom, #b3d8ff, #b3d8ff) left top no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) right top no-repeat,
  linear-gradient(to bottom, #b3d8ff, #b3d8ff) right top no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) left bottom no-repeat,
  linear-gradient(to bottom, #b3d8ff, #b3d8ff) left bottom no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat;
  background-size: 1px 20px, 20px 1px, 1px 20px, 20px 1px;

  span {
    cursor: default;
  }
}

.active {
  box-shadow: inset 0 0 16px 0 #66b1ff;
  font-size: 16px;
  font-weight: bolder;
}
</style>
